package com.whmskj.xjlhsc.controller;

import com.github.pagehelper.PageHelper;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhsc.controller.fo.AOFo;
import com.whmskj.xjlhsc.mobie.energymanage.service.MobileDashboardService;
import com.whmskj.xjlhsc.mobie.energymanage.service.MobileEnergyService;
import com.whmskj.xjlhsc.service.EnergyService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * @Author: Sakura
 * @Date: 2025/8/13 14:17
 * @Version: v1.0.0
 * @Description: TODO
 **/
@RestController
@RequestMapping("/api/energy")
public class EnergyController {

    @Resource
    private MobileEnergyService energyService;

    @Resource
    private MobileDashboardService dashboardService;

    @Resource
    private EnergyService service;

    /**
     * 获取设备能耗概览列表，包含本日、本月、总能耗及实时数据
     * 可按日期和工序筛选
     *
     * @param day     日期，默认为当前日期
     * @param process 工序，可选
     * @return 设备能耗概览列表
     */
    @ApiOperation(value = "能耗概览（分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "day", value = "查询日期，格式：yyyy-MM-dd", required = false, paramType = "query"),
            @ApiImplicitParam(name = "process", value = "工序筛选", required = false, paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页码(默认1)", required = false, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量(默认10)", required = false, paramType = "query"),
            @ApiImplicitParam(name = "body", value = "可选JSON：{pageNum:1,pageSize:10}", required = false, paramType = "body")
    })
    @PostMapping("/overview")
    public AjaxResult overview(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate day,
            @RequestParam(required = false) String process,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestBody(required = false) Map<String, Object> body) {
        if (body != null) {
            if (pageNum == null) {
                Object pn = body.get("pageNum");
                if (pn instanceof Number) pageNum = ((Number) pn).intValue();
                else if (pn instanceof String && !((String) pn).isEmpty()) {
                    try {
                        pageNum = Integer.parseInt((String) pn);
                    } catch (Exception ignored) {
                    }
                }
            }
            if (pageSize == null) {
                Object ps = body.get("pageSize");
                if (ps instanceof Number) pageSize = ((Number) ps).intValue();
                else if (ps instanceof String && !((String) ps).isEmpty()) {
                    try {
                        pageSize = Integer.parseInt((String) ps);
                    } catch (Exception ignored) {
                    }
                }
            }
            if (day == null && body.get("day") instanceof String) {
                day = LocalDate.parse((String) body.get("day"));
            }
            if ((process == null || process.isEmpty()) && body.get("process") instanceof String) {
                process = (String) body.get("process");
            }
        }
        PageHelper.startPage(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        List<Map<String, Object>> list = energyService.overview(day, process);
        return Page.getDataTable(list);
    }

    /**
     * 获取单个设备的能耗详情，包括日能耗曲线、月能耗曲线、实时数据和电能数据汇总
     *
     * @param deviceId 设备ID
     * @return 设备能耗详情
     */
    @ApiOperation(value = "设备能耗详情", notes = "包含日/月能耗曲线、实时数据与电能汇总")
    @ApiImplicitParam(name = "deviceId", value = "设备ID", required = true, paramType = "path")
    @GetMapping("/{deviceId}/detail")
    public AjaxResult detail(@PathVariable Long deviceId) {
        return AjaxResult.success(energyService.deviceDetail(deviceId));
    }

    @GetMapping("/status/stats/default")
    public AjaxResult getDefaultDeviceStatusStats(@RequestParam(required = false) String process) {
        // 复用带工序的统计
        java.util.List<java.util.Map<String,Object>> items = dashboardService.getDeviceStatusStats(process);
        long total = 0L;
        if (items != null) {
            for (java.util.Map<String,Object> row : items) {
                Object c = row.get("count");
                if (c instanceof Number) total += ((Number)c).longValue();
            }
        }
        if (items != null) {
            for (java.util.Map<String,Object> row : items) {
                row.remove("total");
            }
        }
        java.util.Map<String,Object> payload = new java.util.HashMap<>();
        payload.put("total", total);
        payload.put("items", items);
        return AjaxResult.success(payload);
    }

    @GetMapping("/getPz")
    public AjaxResult getPz(@RequestParam(required = false) String process) {
        Object result = service.getPz(process);
        return AjaxResult.success(result);
    }

    @GetMapping("/nhfx")
    public AjaxResult nhfx(@RequestParam(required = false) String month) {
        Object result = service.nhfx(month);
        return AjaxResult.success(result);
    }

    @GetMapping("/nhfxCp")
    public AjaxResult nhfxCp(AOFo fo) {
        return AjaxResult.success(service.nhfxCp(fo));
    }

}
